/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Facility;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.DataService;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.FacilityService;
import me.zhengjie.modules.system.domain.vo.FacilityQueryCriteria;
import lombok.RequiredArgsConstructor;
import java.util.List;

import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author psyduck
* @date 2023-11-07
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：车间管理")
@RequestMapping("/api/facility")
public class FacilityController {

    private final FacilityService facilityService;
    private final DeptService deptService;
    private final DataService dataService;
    private final UserService userService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('facility:list')")
    public void exportFacility(HttpServletResponse response, FacilityQueryCriteria criteria) throws IOException {
        facilityService.download(facilityService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询系统：车间")
    @ApiOperation("查询系统：车间")
    @PreAuthorize("@el.check('facility:list')")
    public ResponseEntity<PageResult<Facility>> queryFacility(FacilityQueryCriteria criteria, Page<Object> page){
        System.out.println(criteria);
        if (!ObjectUtils.isEmpty(criteria.getDeptid())) {
            criteria.getDeptIds().add(criteria.getDeptid());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptid());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        PageResult<Facility> facilityPageResult = facilityService.queryAll(criteria, page);
        return new ResponseEntity<>(facilityPageResult,HttpStatus.OK);
    }



    @PostMapping
    @Log("新增系统：车间")
    @ApiOperation("新增系统：车间")
    @PreAuthorize("@el.check('facility:add')")
    public ResponseEntity<Object> createFacility(@Validated @RequestBody Facility resources){
        facilityService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改系统：车间")
    @ApiOperation("修改系统：车间")
    @PreAuthorize("@el.check('facility:edit')")
    public ResponseEntity<Object> updateFacility(@Validated @RequestBody Facility resources){
        resources.setDeptId(resources.getDept().getId());
        List<Facility> facilities = facilityService.selectAll(resources.getFacility());
        //判断车间是否存在
            for (Facility f:facilities) {
                if (Objects.equals(f.getFacility(), resources.getFacility()) && !f.getId().equals(resources.getId())){
                    throw new EntityExistException(Facility.class,"facility",f.getFacility());
                }
            }

        facilityService.update(resources);
        ResponseEntity<Object> objectResponseEntity = new ResponseEntity<>(HttpStatus.NO_CONTENT);
        System.out.println(objectResponseEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除系统：车间")
    @ApiOperation("删除系统：车间")
    @PreAuthorize("@el.check('facility:del')")
    public ResponseEntity<Object> deleteFacility(@RequestBody List<String> ids) {
        facilityService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}